package com.sys.group.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sys.common.vo.Result;
import com.sys.group.entity.Role;
import com.sys.group.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gyf
 * @since 2023-05-15
 */
@Api(tags = {"角色管理接口"})
@RestController
@RequestMapping("/role")
public class RoleController {
    /*
     * 装配service对象
     * */
    @Autowired
    private IRoleService roleService;


    // 查询所有角色
    @ApiOperation("查询所有角色接口")
    @GetMapping("/all")
    public Result<List<Role>> getAllRole() {
        List<Role> list = roleService.list();
        return Result.success(list);
    }

    @ApiOperation("角色列表接口")
    @GetMapping("/list")
    public Result<Map<String, Object>> getRoleList(
            @RequestParam(value = "rolename", required = false) String name,
            @RequestParam("pageNo") Long pageNo,
            @RequestParam("pageSize") Long pageSize
    ) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name), Role::getName, name);
        wrapper.orderByAsc(Role::getId);

        Page<Role> page = new Page<>(pageNo, pageSize);
        roleService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("roleList", page.getRecords());

        return Result.success(data);
    }

    @ApiOperation("添加角色接口")
    @PostMapping
    public Result<?> addRole(@RequestBody Role role) {
        role.setDeleted(0);
//        System.out.println("addRole: " + role);
        roleService.addRole(role);
        return Result.success("新增角色成功！");
    }

    @ApiOperation("更新角色接口")
    @PutMapping
    public Result<?> updateRole(@RequestBody Role role) {
//        System.out.println("update: " + role);
        roleService.updateRole(role);
        return Result.success("修改角色成功！");
    }

    @ApiOperation("根据id获取角色信息接口")
    @GetMapping("/{id}")
    public Result<Role> getRoleById(@PathVariable("id") Integer id) {
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    @ApiOperation("删除角色接口")
    @DeleteMapping("/{id}")
    public Result<Role> deleteRoleById(@PathVariable("id") Integer id) {
        roleService.deleteRoleById(id);
        return Result.success("删除角色成功！");
    }
}
